package com.erp.erp_ui.Filter;

import com.erp.utils.HttpSessionUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "AuthFilter",
        urlPatterns = "/*"/*通配符（*）表示对所有的web资源进行拦截*/
       /* , initParams = {
             @WebInitParam(name = "charset", value = "utf-8")*//*这里可以放一些初始化的参数*//*
        }*/
        )

public class AuthFilter implements Filter {
    /*private String filterName;
    private String charset;*/

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*初始化方法  接收一个FilterConfig类型的参数 该参数是对Filter的一些配置*/
       /* filterName = config.getFilterName();
        charset = config.getInitParameter("charset");

        System.out.println("过滤器名称：" + filterName);
        System.out.println("字符集编码：" + charset);*/
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain  chain) throws IOException, ServletException {
        /*过滤方法 主要是对request和response进行一些处理，然后交给下一个过滤器或Servlet处理*/
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        if(uri.endsWith("/erp/") || uri.endsWith("login")||uri.endsWith("login.jsp") ||uri.endsWith("getPublicKeyString")){
            chain.doFilter(request, response);//交给下一个过滤器或servlet处理
        }else if((uri.contains(".css") || uri.contains(".js") || uri.contains(".jpg") || uri.contains(".png")
                || uri.contains(".jpng")) && !uri.contains(".jsp")){
            chain.doFilter(request, response);//交给下一个过滤器或servlet处理
        }else
        {
            if(null==HttpSessionUtils.get(((HttpServletRequest)request).getSession().getId())){

                res.addHeader("Access-Control-Allow-Origin", "*");
                PrintWriter out = res.getWriter();
                out.println("<script language='javascript' type='text/javascript'>");
                out.println("window.history.forward(-1); ");
                out.println("location.replace('" + req.getContextPath() + "/views/jsp/login.jsp');   ");// event.returnValue=false;
                out.println("window.top.location.href='" + req.getContextPath() + "/views/jsp/login.jsp'");

                out.println("</script>");
               // res.sendRedirect("/erp/views/jsp/login.jsp");
               // req.getRequestDispatcher("/erp/views/jsp/login.jsp").forward(req,res);
            }else{
                chain.doFilter(request, response);//交给下一个过滤器或servlet处理
            }
        }



    }

    @Override
    public void destroy() {
        /*销毁时调用*/
    }
}
